#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>

/**@fn char * GetLogTime()
* @brief 以字符串形式获取当前时间
* @brief Author/Date	hkm/2019-03-28
* @param [in] 
* @return 返回字符串的首地址
*/
static char * GetLogTime()
{
    static char time_buf[128] = {0};
    struct tm *p;
    time_t timep;

    timep = time(NULL);

    p=localtime(&timep);

    memset(time_buf, 0, sizeof(time_buf));
    sprintf(time_buf, "%04d-%02d-%02d  %02d:%02d:%02d ", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, 
                                        p->tm_hour, p->tm_min, p->tm_sec);
    
    return time_buf;
}



int DailyAdd(char *log)
{
	char *dailyFile = "cpuUse.txt";
    FILE   *fp = fopen(dailyFile, "a+");
    if(NULL == fp){
        return -1;
    }

    char buf[2048] = {0};
    sprintf(buf, "[%s] %s \n", GetLogTime(), log);
    fwrite(buf, strlen(buf), 1, fp);

    fclose(fp);
    return 0;

}


/**--------------------------------------------------------------------------------
* 函数名称 :	getCpuTime
* 功能描述 :	获取CPU时间
* 入口参数 :	无
* 编辑作者 :	hkm
* 返回值   ：   成功返回CPU使用时间，失败返回0
* 备  注   ：   
---------------------------------------------------------------------------------*/
unsigned int getCpuTime()
{
	FILE *fp;
	char buf[1024];
	char *str;
	unsigned int data[10];
	unsigned int sum = 0;
	int i = 0;
	const char *path = "/proc/stat";  
	
	fp = fopen(path, "r");
	if(fp == NULL){
		printf("open failed \n");
		perror("fopen");
		return 0;
	}
	memset(buf, 0, sizeof(buf));
	fgets(buf, sizeof(buf), fp);
	fclose(fp);
	str = strstr(buf, "cpu");
	if(NULL == str){
		return 0;
	}
	
	
	sscanf(str, "%*[^ ] %d %d %d %d %d %d %d %d %d %d ", &data[0],&data[1],&data[2],
		&data[3],&data[4],&data[5],&data[6],&data[7],&data[8],&data[9]);
		
	for(i=0; i<10; i++){
		sum += data[i];
	}
	
	return sum;
}

/**--------------------------------------------------------------------------------
* 函数名称 :	GetProgressTime
* 功能描述 :	获取进程占用CPU时间
* 入口参数 :	unsigned int pid	进程号
* 编辑作者 :	hkm
* 返回值   ：   成功返回进程占用CPU时间，失败返回0
* 备  注   ：   
---------------------------------------------------------------------------------*/
unsigned int GetProgressTime(unsigned int pid)
{
	unsigned time_sum = 0;
	char buf[1024] = {0};
	char path[128] = {0};
	char tmp[16] = {0};
	FILE *fp = NULL;
	unsigned int data[4] = {0};
	int i = 0;
	char *str = NULL;
	
	sprintf(path, "/proc/%d/stat", pid); 
	
	fp = fopen(path, "r");
	if(NULL == fp){
		printf("open path %s failed \n",path);
		perror("fopen");
		return 0;
	}
	
	fgets(buf, sizeof(buf), fp);
	fclose(fp);
	sprintf(tmp, "%d", pid);
	str = strstr(buf, tmp);
	if(NULL == str){
		printf("not find the pid %d \n",pid);
		return 0;
	}
	
	sscanf(str, "%*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %*[^ ] %d %d %d %d",
				&data[0], &data[1], &data[2], &data[3]);
	for(i=0; i<4; i++){
		time_sum += data[i];
	}		
	
	return time_sum;
	
}

/**--------------------------------------------------------------------------------
* 函数名称 :	GetPID
* 功能描述 :	根据进程名字查找进程的进程号
* 入口参数 :	char *prog  字符串，进程名
* 编辑作者 :	hkm
* 返回值   ：   成功返回大于0的进程号，失败返回-1
* 备  注   ：   
---------------------------------------------------------------------------------*/
int GetPID(char *prog)
{
	if(NULL == prog){
		printf("param is NULL");
		return -1;
	}
	
	FILE *fp;
	char buf[512] = {0};
	int pid = 0;
	fp = popen("ps", "r");
	if(!fp){
		perror("popen");
		return -1;
	}
	
	while(!feof(fp)){
		memset(buf, 0, sizeof(buf));
		fgets(buf, sizeof(buf), fp);
		if(strstr(buf, prog)){
			break;
		}
	}

	pclose(fp);
	pid = atoi(buf);
	printf("progress %s pid = %d \n", prog, pid);
	
	return pid;
}


/**--------------------------------------------------------------------------------
* 函数名称 :	main
* 功能描述 :	获取某个进程在2s时间内占用CPU时间与CPU总时间的百分比
* 入口参数 :	
* 编辑作者 :	hkm
* 返回值   ：   返回0：成功  -1：失败
* 备  注   ：   
---------------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
	unsigned int totol_time_old;
	unsigned int totol_time_new;
	unsigned int progress_time_old;
	unsigned int progress_time_new;
	unsigned int percent;
	int pid = 0;
	char buf[1024] = {0};
	
	//if(argc < 2){
	//	printf("input note: %s file \n", argv[0]);
	//	return -1;
	//}
	printf("****************** \n");
	
	pid = GetPID("test_lora");
	if(pid < 0){
		return -1;
	}
	
	while(1){
		totol_time_old = getCpuTime();
		progress_time_old = GetProgressTime(pid);
		sleep(2);
		totol_time_new = getCpuTime();
		progress_time_new = GetProgressTime(pid);
		
		percent = 1000 * (progress_time_new - progress_time_old) / 
						(totol_time_new - totol_time_old);
		memset(buf, 0, sizeof(buf));
		sprintf(buf, "pid %d percent by cpu : %d.%d%% \n", pid, percent/100, percent%100);
		DailyAdd(buf);
		sleep(30);
	}
	
	return 0;
}